<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/1/18
 * Time: 20:51
 * Desc: 门店商品列表
 */
namespace app\index\controller;
use app\index\service\PointService;
use think\Controller;
use think\Db;
use app\index\controller\Base;
//use app\comm\controller\WebLogController;
use app\index\service\GoodsListService;
use app\index\service\WeixinService;
use app\comm\service\DadaOpenapi;

class GoodsList extends Base{

    public function _initialize(){
        parent::_initialize();
        $cur_city = db('city')->where('key',cookie('city_key'))->value('value');        //当前城市

        $this->assign('realname',session('_user_uid_.realname'));
        $this->assign('cur_city',$cur_city);
        $this->assign('url',request()->url(true));

        $sql = "SELECT id,name,logo,cat_id FROM ys_goods AS a WHERE 6> (SELECT COUNT(*) FROM ys_goods WHERE cat_id=a.cat_id AND id>a.id) AND a.is_online=1 AND a.status=1 AND a.is_deleted=0 AND is_top>0 ORDER BY a.id DESC";
        $tui_goods = Db::query($sql);
        $this->assign('tui_goods',$tui_goods);
    }

    /**
     * @Author  lingyun
     * @Desc    门店商品列表页面
     */
    public function goods_list(){
        $service = new GoodsListService();
        $service->goods_list();

        return $this->fetch('goods_list');
    }

    /**
     * @Author  lingyun
     * @Desc    会员商品列表
     * 2018-05-18
     */
    public function member_goods_list(){
        $service = new GoodsListService();
        $service->member_goods_list();

        return $this->fetch('goods_list');
    }

    /**
     * @Author  lingyun
     * @Desc    商品详情页
     */
    public function goods_detail(){
        $service = new GoodsListService();
        if($service->goods_detail() === false){
            return $this->fetch('public/error');
        }else{
            return $this->fetch('goods_detail');
        }

    }

    /**
     * @Author  lingyun
     * @Desc    获取ajax评论
     */
    public function get_ajax_comment(){
        $page = input('cur_page');              //当前页码
        $goods_id = input('goods_id');              //商品id
        $service = new GoodsListService();
        $service->get_ajax_comment($page,$goods_id);
    }

    /**
     * @Author  lingyun
     * @Desc    获取可购买的代金券
     */
    public function get_cash_coupon_list(){
        $service = new GoodsListService();
        $service->get_cash_coupon_list();

        return $this->fetch('goods_list');
    }

    /**
     * @Author  lingyun
     * @Desc    代金券详情
     * 2018-05-04
     */
    public function cash_coupon_detail(){
        $service = new GoodsListService();
        $service->get_cash_coupon_detail();

        return $this->fetch('coupon_detail');
    }

    /**
     * @Author  lingyun
     * @Desc    加入购物车前 -- 弹出的选择商品属性弹窗 -- 预选择属性
     */
    public function pre_addto_cart(){
        //门店id
        $store_id = session('store_id');
        //store_goods_stock -> goods_id
        //ys_store_recommend_goods => goods_id => ys_store_stock_goods =>id
        $id = input('id');      //goods_id
        $goods = db('store_goods_stock')->alias('a')->join('ys_goods_spec_detail b','a.goods_spec_id=b.id','LEFT')->where('a.id',$id)->field('a.*,b.price as goods_price')->find();
        $where = [
            'goods_id'=>$goods['goods_id'],
            'store_id'=>$store_id,
        ];
        //商品属性主键id   ys_goods_spec_detail => 主键id
        $goods_spec_id = db('store_goods_stock')->where($where)->column('goods_spec_id');    //array(62,,61,60)
        $goods_spec_id = implode(',',$goods_spec_id);
        //ys_spec_detail => specs
        $specs = db('goods_spec_detail')->where('id','in',$goods_spec_id)->column('specs');
        $specs = implode(',',$specs);                   //169,170,171
        $specs = implode(',',array_unique(explode(',',$specs)));        //将转换的字符串去重
        //ys_goods_spec  => spec_id
        $spec_result = db('goods_spec')->where('id','in',$specs)->column('id,goods_id,spec_id,detail');
        $spec_id = array_values(array_unique(array_column($spec_result, 'spec_id')));        //取出某一列的值 -- 数组
        $spec_id = implode(',',$spec_id);
        //商品属性分类： 尺寸、温度
        $spec_name = db('goods_spec_name')->where('id','in',$spec_id)->column('id,name,addtime');


        $this->assign('spec_result',$spec_result);
        $this->assign('spec_name',$spec_name);
        //商品属性分类的种类
        $this->assign('spec_count',count($spec_name));
        $this->assign('goods',$goods);
        return $this->fetch('pre_addto_cart');
    }

    /**
     * @Author  lingyun
     * @Desc    选择属性，预计算价格
     */
    public function pre_calculate_price(){
        $service = new GoodsListService();
        $service->pre_calculate_price();
    }

    /**
     * @Author  lingyun
     * @Desc    腾讯地图api计算两点之间的距离
     */
    public function count_dis(){
        $url = "http://apis.map.qq.com/ws/distance/v1/?parameters&from=35.95166,120.15944&to=35.958496749206,120.21075979183&key=SCIBZ-DHYCX-RQZ4A-ZZB2V-2VHPH-N4FUM";
        $result=file_get_contents($url);
        halt(json_decode($result,true));
    }

    /**
     * @Author  lingyun
     * @Desc    加入购物车
     */
    public function addto_cart(){
        $service = new GoodsListService();
        $service->addto_cart();
    }

    /**
     * @Author  lingyun
     * @Desc    预生成订单 -- 立即购买
     * 2018-04-23   pc端提交订单信息
     */
    public function pre_create_order(){
        $post = input('param.');
        $store_id = cookie('store_id');
        $store = db('store')->where('id',$store_id)->field('id,address,is_jiameng,mobile')->find();
        if(empty($post['p_id'])){
            $this->assign('err_msg','请选择先选购商品');
            $this->assign('err_url',url('GoodsList/goods_list'));
            $this->assign('err_button','选购商品');
            return $this->fetch('public/error');
            exit();
        }

        $post['id'] = implode(',',$post['p_id']);         //store_goods_stock => id
        $uid = session('_user_uid_.uid');
        $store_id = cookie('store_id');
        if(empty($uid)){        //登录
            $this->redirect('Login/loginin');
        }
        if(empty($store_id)){       //选择门店
            $this->redirect('Index/index');
        }

        //会员信息 -- 查询会员余额
        $member = db('user')->where('uid',$uid)->field('uid,user_money,openid,level_id')->find();
//        halt($post);

//        $post['spec_id'] = explode(',',trim($post['p_spec_id'],','));

        //检查商品属性，判断库存是否充足，改属性的商品是否上架
//        $spec_detail = '';
//        for($i=1;$i<=$post['p_spec_count'];$i++){
//            $key = 'spec_'.$i;
//            $spec_detail .= $post[$key].',';
//        }
        $spec_detail = trim($post['p_spec_id'],',');        //商品属性
        $where = [
            'a.store_id'=>$store_id,
            'a.goods_id'=>$post['p_goods_id'],
            'a.id'=>$post['id']
        ];
//        $goods = db('store_goods_stock')->alias('a')->join('ys_goods_spec_detail b','a.goods_spec_id=b.id','LEFT')->where($where)->field('a.*,b.price')->find();
        $goods = db('store_goods_stock')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->join('ys_goods_spec_detail c','a.goods_spec_id=c.id','LEFT')->where($where)->field('a.*,b.logo,b.name,b.cat_id,b.unit,b.member_level_id,c.price as goods_price,c.member_price')->find();          //查询购买的商品

        if(empty($goods)){
//            $this->error('该商品已下架，请购买其它商品',url('GoodsList/goods_list'));
            $this->assign('err_msg','该商品已下架，请购买其它商品');
            $this->assign('err_url',url('GoodsList/goods_list'));
            $this->assign('err_button','选购商品');
            return $this->fetch('public/error');
            exit();
        }else if($goods['stock'] <=0){
//            $this->error('该商品库存不足，请选择其他商品',url('GoodsList/goods_list'));
            $this->assign('err_msg','该商品库存不足，请购买其它商品');
            $this->assign('err_url',url('GoodsList/goods_list'));
            $this->assign('err_button','选购商品');
            return $this->fetch('public/error');
        }else if($goods['onsale'] == 0){
//            $this->error('该商品已经下架，请选择其它商品',url('GoodsList/goods_list'));
            $this->assign('err_msg','该商品已经下架，请购买其它商品');
            $this->assign('err_url',url('GoodsList/goods_list'));
            $this->assign('err_button','选购商品');
            return $this->fetch('public/error');
        }else if($goods['is_deleted'] == 1){
//            $this->error('该商品已经下架，请选择其它商品',url('GoodsList/goods_list'));
            $this->assign('err_msg','该商品已经下架，请购买其它商品');
            $this->assign('err_url',url('GoodsList/goods_list'));
            $this->assign('err_button','选购商品');
            return $this->fetch('public/error');
        }

//        if(!empty($post['num'])){
//            $num = $post['num'];
//        }else{
//            $num = $post['s_num'];
//        }
        //***************确定会员商品价格*****************//
        $num = $post['num'];
        //2018-05-17   修改
//        if($member['level_id'] >= $goods['member_level_id'] && $member['level_id'] != 1){            //会员价
//            $total_amount = $goods['member_price']*$num;      //订单总价
//            $goods['goods_price'] = $goods['member_price'];
//        }else{
//            $total_amount = $goods['goods_price']*$num;      //订单总价
//        }
        //2018-05-17修改

        if($goods['member_level_id'] !=1 && $member['level_id'] >= $goods['member_level_id']){            //会员价
            $total_amount = $goods['member_price']*$num;      //订单总价
            $goods['goods_price'] = $goods['member_price'];
        }else{
            $total_amount = $goods['goods_price']*$num;      //订单总价
        }

        $goods_list[0] = $goods;     //将商品信息转成二维数组
        $delivery_fee = 0;      //计算运费
        $address_id = 0;        //默认地址id

        //默认收货地址,计算默认地址的运费
        $address_list = db('user_address')->where(['uid'=>$uid,'deleted'=>0])->order('id desc')->select();        //全部地址列表
        $address = db('user_address')->where(['uid'=>$uid,'is_default'=>1])->find();            //默认收货地址
        if(!empty($address)){
            $result = $this->count_delivery_fee($address['address']);

            if($result['code'] == 0){
                $delivery_fee = 0;
                $address_id  = 0;
            }else{
                $delivery_fee = $result['msg'];
                $address_id = $address['id'];
            }
        }
        $final_amount = $delivery_fee+$total_amount;        //最终支付金额

        $city_list = db('city')->where(['status'=>1,'is_deleted'=>0])->select();
        $coupon = $this->get_coupon_list($final_amount,$goods['cat_id']);      //优惠券列表
        $cash_coupon = $this->get_cash_coupon($goods['cat_id'],$final_amount);
        $count_coupon = count($coupon);
        $count_cash_coupon = count($cash_coupon);


        $category = get_top_category();           //商品顶级分类
        $exp_category = get_exp_category();       //商品扩展分类
        if(isMobile()){
            if(is_weixin()){
                $this->assign('is_mobile',0);
            }else{
                $this->assign('is_mobile',1);
            }
        }else{
            $this->assign('is_mobile',0);
        }

//        $this->assign('order_sn',$order_sn);            //订单编号
        $this->assign('city',$city_list);                      //城市列表
        $this->assign('address',$address_list);              //默认收货地址
        $this->assign('goods',$goods_list);                  //商品
        $this->assign('num',$num);              //购买数量
        $this->assign('total_amount',$total_amount);    //订单总价
        $this->assign('address_id',$address_id);        //默认收货地址
        $this->assign('delivery_fee',$delivery_fee);    //运费
        $this->assign('final_amount',$final_amount);    //最终金额
        $this->assign('member',$member);                //余额
        $this->assign('nowtime',date('Y-m-d',time()));
        $this->assign('order_sn',create_order_sn($uid));      //订单编号
        $this->assign('coupon',$coupon);                //优惠券
        $this->assign('cash_coupon',$cash_coupon);      //代金券
        $this->assign('count_coupon',$count_coupon);      //代金券
        $this->assign('count_cash_coupon',$count_cash_coupon);      //代金券
        $this->assign('category',$category);      //代金券
        $this->assign('exp_category',$exp_category);      //代金券
        $this->assign('default_address',$address);      //默认收货地址
        $this->assign('store_info',$store);      //默认收货地址
        if(is_weixin()){
            $this->assign('is_weixin',1);
        }else{
            $this->assign('is_weixin',0);
        }

        return $this->fetch('pre_create_order');
    }

    /**
     * @Author  lingyun
     * @Desc    查询订单运费
     */
    public function get_delivery_fee(){
        $receive_location = input('address');
        $key= Db::name('dic_config')->where('name','tx_key')->find();
        $url='http://apis.map.qq.com/ws/distance/v1/?parameters'.$receive_location.'&key='.$key['value'];

        $post = input('post.');
        $result = countDeliveryFee($post['address'],session('store_id'));
        if($result['code'] == 0){
//            $delivery_fee = 0;
            $this->error('运费查询失败','',$result['msg']);
        }else{
//            $delivery_fee = $result['msg'];
            $this->success('运费查询成功','',$result['msg']);
//            $address_id = $address['id'];
        }
    }

    /**
     * @Author   lingyun
     * @Desc     根据订单的金额获取会员的优惠券  --  立即购买
     * @Desc     门店的关注券 -- 门店的优惠券
     * @Param    $total_amount -- 门店的优惠券
     * @Param    $cate_id-- 门店的优惠券
     */
    public function get_coupon_list($total_amount,$cate_id){
        $request = request();
//        if($request->isPost()){
//
//        }else{
            $uid = session('_user_uid_.uid');        //会员id
            $store_id = cookie('store_id');         //门店id
            $post = input('param.');                 //代金券金额
//            if(empty($store_id)){
//                $this->error('请选择门店',url('Changestore/index'));
//            }
            //门店普通优惠券
            //商品优惠券，1关注券 ， 2现金券
            $time = time();         //当前的时间
            $where_coupon_0 = [
                'a.store_id'=>$store_id,
                'a.uid'=>$uid,
                'a.is_used'=>0,
                'a.type'=>['neq','2'],
                'a.morethan'=>['elt',$total_amount],
                'a.use_start_time'=>['lt',$time],
                'a.use_end_time'=>['gt',$time],
                'a.cat_id'=>['in','0,'.$cate_id],     //优惠券的类型
                'a.status'=>1
            ];
//            halt($where_coupon_0);
            //普通优惠券 -- 关注券列表
            $coupon = db('user_ycard')->alias('a')->join('ys_store_coupon b','a.coupon_id=b.id','LEFT')->field('a.*,b.img')->where($where_coupon_0)->select();
//            if(!empty($coupon)){
//                foreach($coupon as $k => $v){
//                    $coupon[$k]['reduce'] = (int)$v['reduce'];
//                }
//            }

//            halt($coupon);
            return $coupon;

//            $this->assign('coupon',$coupon);
//
//            return $this->fetch('coupon_list');
//        }
    }

    /**
     * @Author  lingyun
     * @Desc    根据订单的金额获取会员的代金券
     * @Param   $cate_id 商品分类
     */
    public function get_cash_coupon($cate_id,$total_amount){
        $uid = session('_user_uid_.uid');        //会员id
        $store_id = session('store_id');        //门店id
        $post = input('param.');
        $time = time();         //当前时间
        $where = [
            'a.uid'=>$uid,
            'a.store_id'=>$store_id,
            'a.is_used'=>0,
            'a.type'=>2,
            'a.cat_id'=>['in','0,'.$cate_id],
            'a.status'=>1,
            'a.morethan'=>['egt',$total_amount],
            'a.use_start_time'=>['lt',$time],
            'a.use_end_time'=>['gt',$time],
        ];
//halt($where);
        //代金券列表
        $coupon = db('user_ycard')->alias('a')->join('ys_store_coupon b','a.coupon_id=b.id','LEFT')->where($where)->field('a.*,b.img')->select();
//        $this->assign('coupon',$coupon);
//        return $this->fetch('cash_coupon');
        return $coupon;
    }



    /**
     * @Author  lingyun
     * @Desc    获取收货地址
     */
    public function get_address_list(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            $post['uid'] = session('_user_uid_.uid');
            //检测收货地址是否正确
            $result = check_address($post['address']);
            if($result['code'] == 0){
                $this->error($result['msg'],'');
            }
            if($post['is_default'] == 1){
                db('user_address')->where(['uid'=>$post['uid']])->update(['is_default'=>0]);
            }
            $res = db('user_address')->insertGetId($post);
            $post['id'] = $res;
            $res>0?$this->success('保存成功','',$post):$this->error('保存失败','');
        }else{
            $uid = session('_user_uid_')['uid'];
            $address = db('user_address')->where('uid',$uid)->select();
            $this->assign('address',$address);
            return $this->fetch('address_list');
        }
    }

    /**
     * @Author  lingyun
     * @Desc    添加 -- 编辑收货地址
     * 2018-04-24
     */
    public function add_edit_address(){
        $post = input('post.');
        $post['uid'] = session('_user_uid_.uid');
        //检测收货地址是否正确
        $result = check_address($post['address']);

        $config_arr = config('dada');
        $config_arr['url'] = "http://newopen.imdada.cn/api/order/queryDeliverFee";          //订单详情查询
        $dada_obj = new DadaOpenapi($config_arr);
        $data_arr['origin_id'] = build_order_no().cookie('store_id');
        $store = db('store')->alias('a')->join('ys_city b','a.city_code=b.code','LEFT')->where('a.id',cookie('store_id'))->field('a.*,b.dada_code')->find();            //门店信息
        $data_arr['shop_no'] = $store['dada'];           //门店编号
        $data_arr['city_code'] = $store['dada_code'];           //门店编号
        $data_arr['cargo_price'] = 0.01;           //订单金额
        $data_arr['is_prepay'] = 0;           //是否需要垫付，0否
        $data_arr['receiver_name'] = '一朵';           //是否需要垫付，0否
        $data_arr['receiver_address'] = $post['address'];           //是否需要垫付，0否
        $data_arr['callback'] = 'http://ysbl.fxshe.com/index.php/index/dada/count_delivery_fee';           //是否需要垫付，0否
        $data_arr['receiver_phone'] = $post['mobile'];           //假的测试
        $fee_info = $dada_obj->pre_count_delevety_fee($data_arr);          //与计算订单运费
        $result = json_decode($fee_info,true);
        if(empty($result)){
            $this->error('地址填写有误,请重新填写','');
        }else if($result['status'] =='fail' && $result['code'] != 0){
            $this->error('地址填写错误或超过配送范围，请检查并核实','');
        }

//        $post['lng'] = $result['data']['lng'];      //经度
//        $post['lat'] = $result['data']['lat'];      //纬度
        if(isset($post['is_default']) && $post['is_default'] == 1){
            db('user_address')->where(['uid'=>$post['uid']])->update(['is_default'=>0]);
        }else{
            $is_default = db('user_address')->where(['uid'=>session('_user_uid_.uid'),'is_default'=>1])->find();
            if(empty($is_default)){
                $post['is_default'] = 1;
            }
        }
        $res = db('user_address')->insertGetId($post);
        $post['id'] = $res;
        $res>0?$this->success('保存成功','',$post):$this->error('网络请求失败，请重试','');
    }

    /**
     * @Author  lingyun
     * @Desc    预先支付订单
     * @Desc    ys_order、ys_order_details、ys_order_action、ys_user_ycard、ys_user_point_log、ys_pay_log、ys_store_goods_stock
     */
    public function pre_pay_order(){
        $service = new GoodsListService();
        $post = input('post.');
        if(cookie('store_id') == ''){
//            $this->error('请选择城市',url('Index/index'));
            $this->assign('err_msg','当前门店为空，请先选择门店');
            $this->assign('err_url',url('Index/index'));
            $this->assign('err_button','选择门店');
            return $this->fetch('public/error');
            exit();
        }

        $result = $service->check_pay_order($post);
        if($result['code'] == 0){
            $this->assign('err_msg',$result['error_msg']);
            $this->assign('err_url',$result['err_url']);
            $this->assign('err_button',$result['err_button']);
            return $this->fetch('public/error');
            exit();
        }else{
            if($post['pay_type'] == 1){     //支付宝
                $this->redirect(url('Alipay/pay').'?order_sn='.$result['order_sn']);
            }else if($post['pay_type'] == 2){
                if(is_mobile() && !is_weixin()){            //移动支付
//                    halt('sss');
                    $this->redirect(url('Wxpaymobile/h5Pay_order').'?order_sn='.$result['order_sn']);
                }
                $this->redirect(url('Weixinpay/weixin_pay').'?order_sn='.$result['order_sn']);
            }else{
                $this->redirect(url('GoodsList/pay_by_credit').'?order_sn='.$result['order_sn']);
//                $this->pay_by_credit($result['order_sn'],$result['final_amount']);
//                $this->pay_by_credit($result['order_sn'],$result['final_amount']);
            }
        }
    }

    /**
     * @Author  lingyun
     * @Desc    使用余额进行支付
     */
    public function pay_by_credit($order_sn=0,$final_amount=0){
        $uid = session('_user_uid_.uid');
        if(empty($uid)){
            $this->redirect('Login/loginin');
        }

        $order = db('order')->where('order_sn',$order_sn)->find();
        $store = db('store')->where('id',$order['store_id'])->find();           //门店详细信息
        if(empty($order)){
            $this->assign('err_msg','找不到订单信息，请重新下单');
            $this->assign('err_url',url('GoodsList/goods_list'));
            $this->assign('err_button','浏览商品');
            return $this->fetch('public/error');
            exit();
        }
//        if($order['pay_status'] == 1){
//            $this->assign('err_msg','该订单已经支付，请勿重复支付');
//            $this->assign('err_url',url('GoodsList/goods_list'));
//            $this->assign('err_button','浏览商品');
//            return $this->fetch('public/error');
//            exit();
//        }
//        if($order['addtime']+3600<time()){
//            $this->assign('err_msg','改定带已过期，请重新下单');
//            $this->assign('err_url',url('GoodsList/goods_list'));
//            $this->assign('err_button','浏览商品');
//            return $this->fetch('public/error');
//            exit();
//        }
        $member = db('user')->where('uid',$uid)->field('uid,user_money,realname,openid')->find();
        if($order['pay_status'] == 0){
            if($member['user_money'] < $order['final_amount']){
                $this->assign('err_msg','您的余额不足，请先去充值在进行余额付款');
                $this->assign('err_url',url('User/recharge'));
                $this->assign('err_button','去充值');
                return $this->fetch('public/error');
                exit();
            }
        }

        if($order['pay_status'] == 0){
            //构造余额支付记录数据
            $data_arr = [
                'uid'=>$uid,
                'admin_id'=>0,
                'store_id'=>$order['store_id'],
                'order_id'=>$order['id'],
                'order_sn'=>$order['order_sn'],
                'pay_time'=>time(),
                'pay_status'=>1,
                'pay_type'=>3,
                'amount'=>$order['final_amount'],
                'cur_amount'=>$member['user_money']-$order['final_amount'],
                'sign'=>2,
                'chargetype'=>1,
                'charge_cn'=>'线上购买商品，订单号'.$order['order_sn'].'，总价：'.$order['final_amount'],
                'addtime'=>time()
            ];
            //记录余额记录
            db('user_wallet_log')->data($data_arr)->insert();       //记录余额记录

            $pay_log_arr = [
                'order_id'=>$order['id'],
                'order_sn'=>$order['order_sn'],
                'order_type'=>1,
                'uid'=>$uid,
                'pay_type'=>3,
                'pay_sign'=>1,
                'store_id'=>$order['store_id'],
                'amount'=>$order['final_amount'],
                'remark'=>'线上购买商品，订单号'.$order['order_sn'].'，总价：'.$order['final_amount'],
                'addtime'=>time()
            ];
            db('pay_log')->data($pay_log_arr)->insert();            //记录支付记录

            //更新需要向门店进行转账的金额
            $store_amount_arr = [
                'credit'=>$store['credit']+$order['final_amount'],
                'total_amount'=>$store['total_amount']+$order['final_amount'],
                'user_money'=>$store['user_money']+$order['final_amount']
            ];
            db('store')->where('id',$order['store_id'])->update($store_amount_arr);

            $store_credit_log = [
                'store_id' => $order['store_id'],
                'order_id' => $order['id'],
                'type' => 1,
                'credit' => $order['final_amount'],
                'cur_credit' => $store['total_amount'] + $order['final_amount'],
                'remark' => '销售商品收入',
                'addtime' => time(),
                'order_type' => 1,
                'order_sn' => $order['order_sn'],
                'pay_type' => 3
            ];

            db('store_credit_log')->insert($store_credit_log);

            $cur_amount = $member['user_money'] - $order['final_amount'];    //会员当前的余额
            db('user')->where('uid',$uid)->update(['user_money'=>$cur_amount]);     //更新会员当前的余额
//        halt($res);
            if($order['is_ziqu'] == 1){         //自取订单直接完成
                db('order')->where('order_sn',$order_sn)->update(['pay_status'=>1,'pay_time'=>time(),'order_status'=>4,'remark'=>'已支付']);      //更新订单支付状态
                db('order_details')->where('order_id',$order['id'])->update(['status'=>4]);     //更新订单详情的支付状态
                $r_remark = '已支付，待取货';
            }else{
                db('order')->where('order_sn',$order_sn)->update(['pay_status'=>1,'pay_time'=>time(),'order_status'=>1,'remark'=>'已支付']);      //更新订单支付状态
                db('order_details')->where('order_id',$order['id'])->update(['status'=>1]);     //更新订单详情的支付状态
                $r_remark = '已支付，待收货';
            }

            


            //更新优惠券的使用情况
            db('user_ycard')->where('id',$order['coupon_id'])->update(['order_id'=>$order['id'],'used_time'=>time(),'is_used'=>1]);
            db('user_ycard')->where('id',$order['cash_coupon_id'])->update(['order_id'=>$order['id'],'used_time'=>time(),'is_used'=>1]);


            //更新门店库存
            $order_details = db('order_details')->where('order_id',$order['id'])->select();
            foreach($order_details as $k => $v){
//                db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->setDec('stock',$v['goods_num']);
                $stock = db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->find();
                $cur_stock = $stock['stock'] - $v['goods_num'];
                //更新门店库存
                db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->update(['stock'=>$cur_stock]);
                $arr = [
                    'goods_id'=>$v['goods_id'],
                    'goods_spec_id'=>$stock['goods_spec_id'],
                    'title'=>$v['spec_detail'],
                    'order_id'=>$order['id'],
                    'store_id'=>$order['store_id'],
                    'types'=>2,
                    'ruku_num'=>0,
                    'tuihuo_num'=>0,
                    'chuku_num'=>$v['goods_num'],
                    'sunhao_num'=>0,
                    'remark'=>'售卖'.$v['goods_num'],
                    'cur_stock'=>$cur_stock,
                    'addtime'=>time(),
                    'order_sn'=>$order['order_sn'],
                ];
                db('store_goods_log')->insert($arr);
            }



            //订单动作数据
            $data_action = [
                'uid'=>$order['uid'],
                'order_id'=>$order['id'],
                'action_user'=>0,
                'order_status'=>1,
                'pay_status'=>1,
                'status_desc'=>$r_remark,
                'storeid'=>$order['store_id'],
                'addtime'=>time()
            ];
            db('order_action')->data($data_action)->insert();       //新增订单数据

            //支付回调进行三级分销积分变更
            third_tier_distribution($uid,$order['final_amount'],$order['store_id'],$order['id'],0,$order['order_sn']);


            //存在会员的openid就推送模板消息
            if(!empty($member['openid'])){
                //推送模板消息
                $array = [
                    "type"   	  =>1,
                    "touser" 	  =>$member["openid"],
                    "template_id"=>config("mobanid.xiadan")["tempid"],
                    "url" 		  =>config("mobanid.xiadan")["url"],
                    "topcolor"  =>"#743A3A",
                    "data"   =>[
                        "first" 	    =>["value"=>"支付成功",        		"color"=>"#743A3A"],
                        "keyword1"		=>["value"=>$order['order_sn'], 		"color"=>"#743A3A"],
                        "keyword2"		=>["value"=>$order['final_amount'], 		"color"=>"#743A3A"],
                        "keyword3"		=>["value"=>"微信支付","color"=>"#743A3A"],
                        "remark"		=>["value"=>"感谢您的购买，请注意查收商品", 			"color"=>"#743A3A"],
                    ]
                ];
                $wein = new WeixinService();
                $rest  = $wein->sendmsg($array);
            }
        }
        //支付成功，跳转至领取优惠券页面
//        $this->success('支付成功',url('PayComplete/get_coupon')."?out_trade_no=".$order_sn,3);

//        $time = time();
//        //可领取的优惠券列表
//        $sql = "select a.*,ifnull(b.coupon_id,0) as is_received from ys_store_coupon as a left join (select coupon_id,store_id,uid from ys_user_ycard where uid=".$order['uid']." and store_id=".$order['store_id'].") as b on a.id=b.coupon_id where a.store_id=".$order['store_id']." and a.condition<=".$order['final_amount']." and a.send_start_time<".$time." and a.send_end_time>".$time." and a.is_deleted=0 and a.type=0 and a.status=1 and a.create_num>a.send_num";
//
//        //优惠券列表
//        $coupon = Db::query($sql);
//
//        $total = count($coupon);
//        $count = 0;         //计算
//        foreach($coupon as $k => $v){
//            if($v['is_received']>0){
//                $count++;
//            }
//        }

        if($order['receive_coupon_id'] != ''){
            $this->assign('result',1);
        }else{
            $this->assign('result',0);
        }
        $category = db('goods_category')->where(['status'=>1,'is_deleted'=>0,'pid'=>0])->select();
        $my_coupon = db('user_ycard')->where(['uid'=>$uid,'store_id'=>cookie('store_id')])->column('coupon_id');
        $coupon = db('store_coupon')->where('id','in',trim($order['receive_coupon_id'],','))->select();
        $this->assign('order_id',$order['id']);
        $this->assign('category',$category);
        $this->assign('coupon',$coupon);
        $this->assign('my_coupon',$my_coupon);
        $this->assign('receive_order_id',$order['id']);
        $this->assign('point',floor($order['final_amount']/2));
        return $this->fetch('zengsong_coupon');

    }

    /**
     * @Author  lingyun
     * @Desc    收藏商品
     */
    public function collect_goods(){
        $post = input('post.');
        $store_id = cookie('store_id');
        if(empty(session('_user_uid_.uid'))){
            $this->error('请先登录，在进行收藏或取消操作','');
        }
        $where = [
            'uid'=>session('_user_uid_.uid'),
            'goods_id'=>$post['goods_id'],
            'store_id'=>$store_id
        ];
        $collect = db('user_collect')->where($where)->find();
        if(empty($collect)){
            $type = 1;
        }else if($collect['status'] == 1){      //取消
            $type = 0;
        }else{
            $type = 1;
        }
        if($type == 1){     //收藏
            if(empty($collect)){
                $data_arr = [
                    'uid'=>session('_user_uid_.uid'),
                    'goods_id'=>$post['goods_id'],
                    'store_id'=>$store_id,
                    'status'=>1,
                    'addtime'=>time()
                ];
                $res = db('user_collect')->data($data_arr)->insert();
                $res>0?$this->success('收藏成功','',1):$this->error('收藏失败','');
            }else{
                $res = db('user_collect')->where($where)->update(['status'=>1]);
                $res!==false?$this->success('收藏成功','',1):$this->error('收藏失败','');
            }
        }else{
            $res = db('user_collect')->where($where)->update(['status'=>0]);
            $res!==false?$this->success('取消成功','',0):$this->error('取消失败','');
        }
    }

    /**
     * @Author  lingyun
     * @Desc    创建代金券订单
     * 2018-05-05
     */
    public function create_cash_coupon_order(){
        $uid = session('_user_uid_.uid');
        if(empty($uid)){
            $this->redirect('Login/loginin');
        }

        $goodslistservice = new GoodsListService();
        $goodslistservice->create_cash_coupon_order();

        return $this->fetch('create_cash_coupon_order');
    }

    /**
     * @Author  lingyun
     * @Desc    购买代金券
     */
    public function buy_cash_coupon(){
        $post = input('post.');
        $uid = session('_user_uid_.uid');
        if(empty($uid)){
            $this->assign('err_msg','您目前还没有登录，请先去去登录');
            $this->assign('err_url',url('Login/loginin'));
            $this->assign('err_button','登录');
            return $this->fetch('public/error');
        }
        if($post['pay_type'] == 1){     //支付宝
            $this->redirect(url('Alipay/buy_cash_coupon')."?id=".$post['id']."&pay_type=".$post['pay_type']);
        }else if($post['pay_type'] == 2){       //微信支付
            if(is_mobile() && !is_weixin()){
                $this->redirect(url('Wxpaymobile/h5pay_cash_coupon')."?id=".$post['id']."&pay_type=".$post['pay_type']);
            }
            $this->redirect(url('Weixinpay/buy_cash_coupon')."?id=".$post['id']."&pay_type=".$post['pay_type']);
        }else{      //余额支付
            $service = new GoodsListService();
            $service->pay_cash_coupon_crdeit($post['id']);
        }
    }

    /**
     * @Author  lingyun
     * @Desc    添加地址检查地址是否正确查询达达运费
     * array(4) {
        ["status"] => string(7) "success"
        ["result"] => array(6) {
        ["distance"] => float(5059)
        ["fee"] => float(18)
        ["deliverFee"] => float(18)
        ["deliveryNo"] => string(36) "Dadad3a658a1f05e419e8f8226c370a5c16f"
        ["insuranceFee"] => float(0)
        ["tips"] => float(0)
        }
        ["code"] => int(0)
        ["msg"] => string(6) "成功"
        }
     */
   public function get_dada_delivery(){
       $address = input('address');
       $root = request()->domain();
       $config_arr = config('dada');
       $config_arr['url'] = "http://newopen.imdada.cn/api/order/queryDeliverFee";          //订单详情查询
       $dada_obj = new DadaOpenapi($config_arr);
       $data_arr['origin_id'] = build_order_no().cookie('store_id');
       $store = db('store')->alias('a')->join('ys_city b','a.city_code=b.code','LEFT')->where('a.id',cookie('store_id'))->field('a.*,b.dada_code')->find();            //门店信息
       $data_arr['shop_no'] = $store['dada'];           //门店编号
       $data_arr['city_code'] = $store['dada_code'];           //门店编号
       $data_arr['cargo_price'] = 0.01;           //订单金额
       $data_arr['is_prepay'] = 0;           //是否需要垫付，0否
       $data_arr['receiver_name'] = '一朵';           //是否需要垫付，0否
       $data_arr['receiver_address'] = $address;           //是否需要垫付，0否
       $data_arr['callback'] = $root.'/index.php/index/dada/count_delivery_fee';           //是否需要垫付，0否
       $data_arr['receiver_phone'] = '18757685769';           //是否需要垫付，0否
       $fee_info = $dada_obj->pre_count_delevety_fee($data_arr);          //与计算订单运费
       $result = json_decode($fee_info,true);
       if(empty($result)){
//           $this->error('地址填写有误,请重新填写','');
           $this->error('运费查询失败,地址填写有误,请重新填写','','');
       }else if($result['status'] =='fail' && $result['code'] != 0){
//            $this->error('地址填写错误或超过配送范围，请检查并核实','');
           $this->error('运费查询失败，地址填写错误或超过配送范围，请检查并核实','','');
       }

       $price = $this->getDeliveryFee($result['result']['distance']);
//       $this->success('查询成功','',$result['result']['fee']);
       $this->success('查询成功','',$price['msg']);

//       halt($result);
//       $result = $dada_obj->getResult();
//       halt($result);
//       halt($dada_obj->getResult());
   }

    /**
     * @Author  lingyun
     * @Desc    计算运费
     * @Param   $address    收货地址
     */
   public function count_delivery_fee($address=''){
       $root = request()->domain();
       $config_arr = config('dada');
       $config_arr['url'] = "http://newopen.imdada.cn/api/order/queryDeliverFee";          //订单详情查询
       $dada_obj = new DadaOpenapi($config_arr);
       $data_arr['origin_id'] = build_order_no().cookie('store_id');
       $store = db('store')->alias('a')->join('ys_city b','a.city_code=b.code','LEFT')->where('a.id',cookie('store_id'))->field('a.*,b.dada_code')->find();            //门店信息
       $data_arr['shop_no'] = $store['dada'];           //门店编号
       $data_arr['city_code'] = $store['dada_code'];           //门店编号
       $data_arr['cargo_price'] = 0.01;           //订单金额
       $data_arr['is_prepay'] = 0;           //是否需要垫付，0否
       $data_arr['receiver_name'] = '一朵';           //是否需要垫付，0否
       $data_arr['receiver_address'] = $address;           //收货地址
       $data_arr['callback'] = $root.'/index.php/index/dada/count_delivery_fee';           //是否需要垫付，0否
       $data_arr['receiver_phone'] = '18757685769';           //是否需要垫付，0否
       $fee_info = $dada_obj->pre_count_delevety_fee($data_arr);          //与计算订单运费
       $result = json_decode($fee_info,true);
       if(empty($result)){
           return ['code'=>0,'msg'=>'地址填写错误或不在配送范围，请检查并核实'];
       }else if($result['status'] =='fail' && $result['code'] != 0){
           return ['code'=>0,'msg'=>'地址填写错误或不在配送范围，请检查并核实'];
//           $this->error('地址填写错误或不在配送范围，请检查并核实','');
       }

       $price = $this->getDeliveryFee($result['result']['distance']);

       return ['code'=>1,'msg'=>$price['msg']];

   }

    /**
     * @Author  lingyun
     * @Desc    计算运费
     * @param $distance
     * @return array
     */
    private function getDeliveryFee($distance){
        $distance = $distance/2/500;
        //查询运费信息
        $data = Db::name('delivery_fee')->where('is_deleted',0)->order('distance asc')->select();
        foreach($data as $k => $v){
            if($distance < $v['distance']){
                return ['code'=>1,'msg'=>$v['price']];
                break;
            }
        }
        $val = end($data);
        return ['code'=>1,'msg'=>$val['price']];
    }


}